package gateway.config.security.auth;

import cn.hutool.core.exceptions.ExceptionUtil;
import common.config.http.HttpStatusEnum;
import common.model.response.base.Result;
import common.util.ResponseUtil;
import gateway.config.security.exception.CustomAccessDeniedException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理登录后访问接口无权限
 *
 * @author 米泽鹏
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {
		if (e instanceof CustomAccessDeniedException) {
			ResponseUtil.out(response, Result.error(((CustomAccessDeniedException) e).getCode(), ExceptionUtil.getSimpleMessage(e)));
		} else {
			ResponseUtil.out(response, Result.error(HttpStatusEnum.FORBIDDEN.getCode(), ExceptionUtil.getSimpleMessage(e)));
		}
	}

}
